<template>
  <div class="cart">
    <scroller>
      <Title>购物车</Title>
      <!-- 购物车列表 -->
      <div class="cartList" v-if="goodsCarts.length>0">
        <van-cell-group inset v-for="item in goodsCarts" :key="item.id">
          <!-- 商品卡片 -->
          <van-swipe-cell>
            <div class="cartGoodsList">
              <!-- 购物车选中框 -->
              <van-checkbox
                @click="changeCheck(item)"
                v-model="item.active"
                checked-color="#f96c2f"
              ></van-checkbox>
              <!-- 商品图片 -->
              <van-image width="80" height="90" :src="item.src" />
              <!-- 商品信息 -->
              <div class="GoodsCarInfo">
                <!-- 商品标题 -->
                <div class="goodsName textTow">{{item.title}}</div>
                <!-- 商品属性 -->
                <div class="goodsParams">规格:{{item.params[0]}} {{item.params[1]}}</div>
                <div class="goodsPrice">
                  <!-- 商品价钱 -->
                  <div class="price">{{item.price}}</div>
                  <van-stepper v-model="item.Num" theme="round" button-size="22" disable-input />
                </div>
              </div>
            </div>
            <!-- 右侧删除滑块 -->
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                @click="removeGoods(item)"
                class="delete-button"
              />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </div>
      <!-- 空状态 -->
      <van-empty
        v-else
        image="https://cdn.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
        image-size="80"
        description="空空如也"
      />
      <!-- 购物推荐 -->
      <van-nav-bar title="购物推荐" />
      <div class="goodsRecommend">
        <Goods :GoodsList="GoodsList" @click.native="ShowGoods"></Goods>
        <!-- 点滴商品空壳 -->
        <div class="goodsBootom"></div>
      </div>
    </scroller>
    <!-- 底部商品总价 -->
    <van-submit-bar
      v-show="isBootBars"
      :price="isGoodsPrice"
      button-text="提交订单"
      @submit="CheckedGoods"
      :disabled="isGoodsNum"
    >
      <!-- 商品全选 -->
      <van-checkbox v-model="goodsActiveAll" @click="GoodsAll" checked-color="#f96c2f">全选</van-checkbox>
    </van-submit-bar>

    <keep-alive>
      <RightAnimate>
        <router-view class="animated" />
      </RightAnimate>
    </keep-alive>
  </div>
</template>

<script>
// // 公用头部
import Title from '@/components/Title/Title.vue'
// // 共同商品展示组件
import Goods from '@/pages/public/IndexGoods/Goods.vue'

// // 公用页面进入动画
import RightAnimate from '@/components/Animate/RightAnimate.vue'

import { mapMutations, mapState } from 'vuex'
import { CarGoods } from '@/api/api.js'
export default {
  name: 'YscShopCart',
  data () {
    return {
      // 购物推荐
      GoodsList: [],
      // 商品全选
      goodsActiveAll: false,
      // 全选按钮禁用
      isDisabled: false,
      // 商品详情切换
      isGoodsInfo: false,
      // 提交订单 show
      isCartOrder: false
    };
  },
  computed: {
    // 购物车列表
    ...mapState(['goodsCarts']),
    // 计算选中商品的价钱
    isGoodsPrice () {
      return this.goodsCarts.filter(item => item.active).reduce((t, items) => t += Number(parseFloat(items.Num * items.price).toFixed(2).split('.').join('')), 0)
    },
    // 判断商品是否全选
    isGoodsCheck () {
      return this.goodsCarts.every(item => item.active === true)
    },
    // 判断购物车列表是否为空
    isBootBars () {
      if (this.goodsCarts.length <= 0) {
        return false
      }
      return true
    },
    // 计算被选商品
    countGoodsLength () {
      return this.goodsCarts.filter(v => v.active === true)
    },
    // 判断商品是否被选中
    isGoodsNum () {
      const num = this.goodsCarts.filter(v => v.active == true)
      if (num.length <= 0) return true
      return false
    }
  },
  components: {
    Title,
    Goods,
    RightAnimate
  },
  created () {
    // 请求商品列表
    this.getGoodsList()
    // 购物车列表
    this.getGoodsCarList()
  },
  mounted () {
    // 切换详情开启
    this.$bus.$on('cartGoodsInfo', res => {
      this.isGoodsInfo = res
    });
    // 切换详情关闭
    this.$bus.$on('goodsInfoBack', res => {
      this.isGoodsInfo = res
    })
    // 下单关闭
    this.$bus.$on('CartBack', res => {
      this.isCartOrder = res
    })
  },
  methods: {
    ...mapMutations(['getGoodsCarList']),
    // 商品选中状态
    changeCheck () {
      // 判断是否被全选
      if (this.isGoodsCheck) return this.goodsActiveAll = true
      // 反之没有全选
      return this.goodsActiveAll = false
    },
    // 请求商品列表
    async getGoodsList () {
      const { data: res } = await CarGoods();
      if (res.status !== 200) return
      // 赋值商品列表
      this.GoodsList = res.data.goodsInfo
    },
    // 删除商品
    removeGoods (item) {
      // 查找删除的元素
      const x = this.goodsCarts.findIndex(x => x.id === item.id)
      // 删除当前存储
      const car = JSON.parse(window.localStorage.getItem('carList'));
      car.splice(x, 1)
      // 从新赋值
      window.localStorage.setItem('carList', JSON.stringify(car))
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });
      setTimeout(() => {
        // 根据id匹配点击项
        this.goodsCarts.splice(x, 1)
        if (this.goodsCarts.length <= 0) this.goodsActiveAll = false
        this.$toast.clear();
      }, 500);
    },
    // 全选商品
    GoodsAll () {
      this.goodsCarts.filter(item => item.active = this.goodsActiveAll)
      // 判断价钱是否为空
    },
    // 购买选中的商品
    CheckedGoods () {
      if (!this.$store.state.myUserInfo.token) {
        // this.$toast.loading({
        //   message: '加载中...',
        //   forbidClick: true,
        //   loadingType: 'spinner',
        //   onClose () {
        //     this.$toast('请先登陆')
        //   }
        // });
        this.$toast('请先登陆')

        return
      }
      // vuex 下单详情
      this.$store.commit('setCartOrder', this.countGoodsLength)
      // 显示下单详情
      this.$router.push('/orderIndex')

    },
    // 进入商品详情
    ShowGoods () {
      this.$router.push('/cartGoodsInfo')
    }
  },
};
</script>

<style lang="less" scoped>
.animated {
  z-index: 101 !important;
}
.cart {
  background-color: #f5f9fa;
  // 购物车
  .van-cell-group {
    margin-top: 10px;
    .cartGoodsList {
      display: flex;
      align-items: center;
      .van-checkbox {
        flex: 10%;
        display: flex;
        justify-content: center;
      }
      // 商品图片
      .van-image {
        flex: 30%;
        border-radius: 5px;
        overflow: hidden;
        margin: 10px 0px;
      }
      // 商品文字信息
      .GoodsCarInfo {
        flex: 60%;
        height: 100%;
        flex-direction: column;
        font-size: 14px;
        padding: 0px 10px;
        box-sizing: border-box;
        // 商品参数
        .goodsParams {
          margin: 5 px 0px;
          font-size: 12px;
          color: #a6a5a5;
        }
        // 商品价钱
        .goodsPrice {
          font-size: 14px;
          font-weight: bold;
          color: #f96c2f;
          display: flex;
          justify-content: space-between;
          .price::before {
            content: "¥";
          }
        }
      }
    }
  }
  // 购物推荐
  .van-nav-bar {
    background-color: transparent;
  }
  .van-hairline--bottom::after {
    border: none !important;
  }
  // 购物推荐列表
}
// 商品垫底高度
.goodsBootom {
  height: 50px;
}
// 商品删除模块
.delete-button {
  height: 100%;
}
// 商品总价
.van-submit-bar {
  bottom: 50px;
  border-top: 0.5px solid #f2f2f2;
  border-bottom: 0.5px solid #f2f2f2;

  // 商品价钱
  .van-submit-bar__price {
    color: #f96c2f;
  }
  // 提交订单
  .van-submit-bar__button--danger {
    background: -webkit-linear-gradient(left, #f96c2f, #f96c2f);
  }
}
</style>
